﻿//using Castle.Core.Logging;
using Qiniu.Common;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.JSON;
using Qiniu.RS;
using Qiniu.RS.Model;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.IO;
//using YunSpace.Abp.Configuration;

namespace YunSpace.Core
{
    /// <summary>
    /// 七牛云帮助类
    /// </summary>
    public class QiniuHelper
    {
        /// <summary>
        /// 日志
        /// </summary>
        //static ILogger Logger { get; set; }
        
        /// <summary>
        /// 是否使用HTTPS
        /// </summary>
        static bool USE_HTTPS = false;

        #region 1. 实例化 七牛云
        /// <summary>
        /// 七牛云实例
        /// </summary>
        static QiniuHelper _Instance = null;

        static string AK { get { return Configs.GetValue("QINIU_AccessKey"); } }
        static string SK { get { return Configs.GetValue("QINIU_SecretKey"); } } 
        static string BUCKET { get { return Configs.GetValue("QINIU_BUCKET"); } }
     
        public static QiniuHelper Instance
        {
            get
            {
                //Logger = NullLogger.Instance;

                if (_Instance == null)
                {
                    // 使用自定义的JSON序列化、反序列化方法
                    JsonHelper.JsonSerializer = new AnotherJsonSerializer();
                    JsonHelper.JsonDeserializer = new AnotherJsonDeserializer();

                    // ZoneID zoneId = ZoneID.CN_East; 
                    // [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
                    // USE_HTTPS = (true|false) 是否使用HTTPS
                    //Config.SetZone(zoneId, USE_HTTPS);


                    // AK = ACCESS_KEY
                    // USE_HTTPS = (true|false) 是否使用HTTPS
                    // 使用前请确保AK和BUCKET正确，否则此函数会抛出异常(比如code612/631等错误)
                    Config.AutoZone(AK, BUCKET, USE_HTTPS);
                    _Instance = new QiniuHelper();
                }
                return _Instance;
            }
        }
        #endregion

        /// <summary>
        /// 上传（来自网络回复的Http）数据流
        /// </summary>
        public HttpResult HttpUploadStream(Stream stream, string saveKey)
        {
            HttpResult result = default(HttpResult);

            string token = this.GetToken();

            try
            {
                //string url = "http://img.ivsky.com/img/tupian/pre/201610/09/beifang_shanlin_xuejing-001.jpg";
                //var wReq = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
                //var resp = wReq.GetResponse() as System.Net.HttpWebResponse;
                //using (var stream = resp.GetResponseStream())
                //{
                //// 请不要使用UploadManager的UploadStream方法，因为此流不支持查找(无法获取Stream.Length)
                //// 请使用FormUploader或者ResumableUploader的UploadStream方法
                //FormUploader fu = new FormUploader();
                //var result = fu.UploadStream(stream, saveKey, token);
                //Console.WriteLine(result);
                //return result;
                //}
                FormUploader fu = new FormUploader();
                result = fu.UploadStream(stream, saveKey, token);
            }
            catch (Exception ex)
            {
                //Logger.Error("Qiniu:UploadStream        : " + ex);
            }
            return result;
        }

        /// <summary>
        /// 获取七牛云的Token
        /// </summary>
        public string GetToken() {
            // 生成(上传)凭证时需要使用此Mac
            // 这个示例单独使用了一个Settings类，其中包含AccessKey和SecretKey
            // 实际应用中，请自行设置您的AccessKey和SecretKey

            Mac mac = new Mac(AK, SK);

            //string bucket = "yunspace";
            //string saveKey = "1.jpg";

            // 上传策略，参见 
            // https://developer.qiniu.com/kodo/manual/put-policy
            PutPolicy putPolicy = new PutPolicy();
            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;
            putPolicy.Scope = string.Format("{0}", BUCKET);

            // 上传策略有效期(对应于生成的凭证的有效期)          
            putPolicy.SetExpires(3600);

            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            //putPolicy.DeleteAfterDays = 1;

            // 生成上传凭证，参见
            // https://developer.qiniu.com/kodo/manual/upload-token            
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);

            return token;
        }

        public string updatefile() {
            Mac mac = new Mac(AK, SK);
            BucketManager bucketManager = new BucketManager(mac);
            //每个operations的数量不可以超过1000个，如果总数量超过1000，需要分批发送
            string[] keys = {
                "uploads/files/path/广州塔/timg.jpg",
                "uploads/files/path/城西银泰城/微信图片_201803271103583.jpg"
            };
            // 空间名
            string Bucket = "new-yunspace";
            List<string> ops = new List<string>();
            foreach (string key in keys)
            {
                string op = bucketManager.UpdateLifecycleOp(Bucket, key, 30);
                ops.Add(op);
            }
            BatchResult ret = bucketManager.Batch(ops.ToArray());
            if (ret.Code / 100 != 2)
            {
                Console.WriteLine("batch error: " + ret.ToString());
            }
            foreach (BatchInfo info in ret.Result)
            {
                if (info.Code == (int)HttpCode.OK)
                {
                    Console.WriteLine("deleteAfterDays success");
                }
                else
                {
                    Console.WriteLine(info.Data.ToString() + "2");
                }
            }
            return "";
        }

        ///// <summary>
        ///// 上传（来自网络回复的Https）数据流
        ///// </summary>
        //public HttpResult HttpsUploadStream(Stream stream, string saveKey)
        //{
        //    Mac mac = new Mac(AppSettings.Qiniu.ACCESSKEY, AppSettings.Qiniu.SECRETKEY);
        //    // 上传文件名
        //    string key = "key";
        //    // 本地文件路径
        //    string filePath = "D:\\tools\\putty.exe";
        //    // 存储空间名
        //    string Bucket = AppSettings.Qiniu.BUCKET;
        //    // 设置上传策略，详见：https://developer.qiniu.com/kodo/manual/1206/put-policy
        //    PutPolicy putPolicy = new PutPolicy();
        //    putPolicy.Scope = Bucket;
        //    putPolicy.SetExpires(3600);
        //    putPolicy.DeleteAfterDays = 1;
        //    string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

        //    //Config config = new Config();
        //    //// 设置上传区域
        //    //config.Zone = Zone.ZONE_CN_East;
        //    //// 设置 http 或者 https 上传
        //    //config.UseHttps = true;
        //    //config.UseCdnDomains = true;
        //    //config.ChunkSize = ChunkUnit.U512K;
        //    // 表单上传
        //    //FormUploader target = new FormUploader(config);
        //    var uploadFromCDN = true;
        //    FormUploader target = new FormUploader(uploadFromCDN);
        //    HttpResult result = target.UploadFile(filePath, key, token, null);
        //    Console.WriteLine("form upload result: " + result.ToString());


        //    //HttpResult result = default(HttpResult);
        //    //// 生成(上传)凭证时需要使用此Mac
        //    //// 这个示例单独使用了一个Settings类，其中包含AccessKey和SecretKey
        //    //// 实际应用中，请自行设置您的AccessKey和SecretKey
        //    //Mac mac = new Mac(AppSettings.Qiniu.ACCESSKEY, AppSettings.Qiniu.SECRETKEY);

        //    ////string bucket = "yunspace";
        //    ////string saveKey = "1.jpg";

        //    //// 上传策略，参见 
        //    //// https://developer.qiniu.com/kodo/manual/put-policy
        //    //PutPolicy putPolicy = new PutPolicy();

        //    //// 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
        //    //// putPolicy.Scope = bucket + ":" + saveKey;
        //    //putPolicy.Scope = string.Format("{0}", AppSettings.Qiniu.BUCKET);

        //    //// 上传策略有效期(对应于生成的凭证的有效期)          
        //    //putPolicy.SetExpires(3600);

        //    //// 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
        //    //putPolicy.DeleteAfterDays = 1;

        //    //// 生成上传凭证，参见
        //    //// https://developer.qiniu.com/kodo/manual/upload-token            
        //    //string jstr = putPolicy.ToJsonString();
        //    //string token = Auth.CreateUploadToken(mac, jstr);

        //    //try
        //    //{
        //    //    //string url = "http://img.ivsky.com/img/tupian/pre/201610/09/beifang_shanlin_xuejing-001.jpg";
        //    //    //var wReq = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
        //    //    //var resp = wReq.GetResponse() as System.Net.HttpWebResponse;
        //    //    //using (var stream = resp.GetResponseStream())
        //    //    //{
        //    //    //// 请不要使用UploadManager的UploadStream方法，因为此流不支持查找(无法获取Stream.Length)
        //    //    //// 请使用FormUploader或者ResumableUploader的UploadStream方法
        //    //    //FormUploader fu = new FormUploader();
        //    //    //var result = fu.UploadStream(stream, saveKey, token);
        //    //    //Console.WriteLine(result);
        //    //    //return result;
        //    //    //}
        //    //    FormUploader fu = new FormUploader();
        //    //    result = fu.UploadStream(stream, saveKey, token);
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    Logger.Error("Qiniu:UploadStream        : " + ex);
        //    //}
        //    //return result;
        //}

    }
}
